package com.blue.common.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.convert.ConvertException;
import cn.hutool.core.convert.impl.CollectionConverter;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class ConvertUtils {

    public static <T> T convert(Type type, Object value) throws ConvertException {
        return Convert.convert(type, value);
    }

    public static <T> T convertIPage(TypeReference<IPage<T>> reference, IPage iPage) throws ConvertException {
        IPage iPageVO = Convert.convert(reference.getType(), iPage);
        Type type = ((ParameterizedType) reference.getType()).getActualTypeArguments()[0];
        iPageVO.setRecords((List) new CollectionConverter(ArrayList.class, type).convert(iPage.getRecords(), null));
        return (T) iPageVO;
    }

    public static <T> T convertIPage(Type type, IPage iPage) throws ConvertException {
        IPage<T> iPageVO = Convert.convert(IPage.class, iPage);
        iPageVO.setRecords((List) new CollectionConverter(ArrayList.class, type).convert(iPage.getRecords(), null));
        return (T) iPageVO;
    }

    public static <T> List<T> convertList(Class<T> elementType, Object value) throws ConvertException {
        return Convert.toList(elementType, value);
    }
}
